package com.takeaway.presenter

import com.takeaway.model.net.ResponseInfo
import com.takeaway.model.net.TakeoutService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

open abstract class NetPresenter {

    val takeoutService: TakeoutService


    val callBack = object : Callback<ResponseInfo> {
        override fun onFailure(call: Call<ResponseInfo>, t: Throwable) {
            // 没有连接上服务器
        }

        override fun onResponse(call: Call<ResponseInfo>, response: Response<ResponseInfo>) {
            if (response.isSuccessful) {
                // 拿到数据
                val responseInfo = response.body()
                if (responseInfo != null) {
                    val code = responseInfo?.code
                    // 这里做处理
                    parserJson(responseInfo?.data)
                }

            } else {
                // 服务器端错误
                errorCallBack()
            }
        }
    }

    abstract fun parserJson(data: String)
    abstract fun errorCallBack()

    init {
        val retrofit = Retrofit.Builder().baseUrl("http://shop/index.php/")
                .addConverterFactory(GsonConverterFactory.create()) // 添加转换器工厂
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
        takeoutService = retrofit.create<TakeoutService>(TakeoutService::class.java)
    }
}